package com.jtlrm.ckd.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.base.sdk.base.net.CommonObserver;
import com.base.sdk.util.DateFormatUtil;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.TitleBarActivity;
import com.jtlrm.ckd.entity.DataShenHeEntity;
import com.jtlrm.ckd.entity.ShengHuaZhiBiaoEntity;
import com.jtlrm.ckd.entity.ShuJuShenHeDetailEntity;
import com.jtlrm.ckd.entity.ShuJuShenHePicEntity;
import com.jtlrm.ckd.entity.event.ShenHeRemarkMessage;
import com.jtlrm.ckd.entity.event.ShenHeUpdate;
import com.jtlrm.ckd.entity.submitEntity.ShengHuaSubmitData;
import com.jtlrm.ckd.entity.submitEntity.ShengHuaSubmitSubData;
import com.jtlrm.ckd.entity.submitEntity.UpdateShenHuaData;
import com.jtlrm.ckd.mvp.model.ShuJuShenHeModel;
import com.jtlrm.ckd.mvp.view.adapter.ShuJuShenDetailHeAdapter;
import com.jtlrm.ckd.util.CommonUtil;
import com.jtlrm.ckd.util.EventBusUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;


import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

public class ShuJuShenHeDetailActivity extends TitleBarActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    ShuJuShenDetailHeAdapter adapter;
    String treatmentId;
    String patientId;
    ShuJuShenHeModel shuJuShenHeModel;
    String measureDate;
    boolean isPass = true;
    String remark;
    TimePickerView timePickerView;

    public static void goDetail(Context context, String treatmentId, String measureDate, String patientId) {
        Intent intent = new Intent(context, ShuJuShenHeDetailActivity.class);
        intent.putExtra("treatmentId", treatmentId);
        intent.putExtra("measureDate", measureDate);
        intent.putExtra("patientId", patientId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        treatmentId = getIntent().getStringExtra("treatmentId");
        measureDate = getIntent().getStringExtra("measureDate");
        patientId = getIntent().getStringExtra("patientId");

        super.onCreate(savedInstanceState);
    }

    @Override
    protected String getTitleText() {
        return "生化数据详情";
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_shu_ju_shen_he_detail);
    }

    @Override
    protected void initView() {
        shuJuShenHeModel = new ShuJuShenHeModel();
        titleBar.imgRight.setImageResource(R.drawable.picture_browse);
        titleBar.imgRight.setVisibility(View.VISIBLE);
        adapter = new ShuJuShenDetailHeAdapter(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(createItemDecoration());
        recyclerView.setAdapter(adapter);
        EventBusUtil.register(this);
        View header = LayoutInflater.from(context).inflate(R.layout.shu_ju_shen_he_header, null);
        final TextView checkDateT = header.findViewById(R.id.check_date);
        // setText(checkDateT, DateFormatUtil.dateFormatLine(System.currentTimeMillis()));
        setText(checkDateT, measureDate);
        adapter.addHeaderView(header);
        timePickerView = new TimePickerBuilder(context, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                measureDate = DateFormatUtil.dateFormatLine(date.getTime());
                setText(checkDateT, measureDate);
            }
        }).build();
        checkDateT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!timePickerView.isShowing()) {
                    timePickerView.show();
                }
            }
        });
    }

    @Override
    protected void obtainData() {
    }

    @Override
    protected void initEvent() {
        titleBar.imgRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadPic();
            }
        });
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadData();
            }
        });
        smartRefreshLayout.autoRefresh();

    }

    ArrayList<String> path = new ArrayList<>();

    private void loadPic() {
        if (path.size() != 0) {
            YinShiTuPianActivity.showTuPian(context, path);
        } else {
            showLoadingDialog("加载中");
            shuJuShenHeModel.queryShenHeDetailPic(treatmentId, new CommonObserver<List<ShuJuShenHePicEntity>>() {
                @Override
                public void onError(int errType, String errMessage) {
                    dismissLoadingDialog();
                    showToast(errMessage);
                }

                @Override
                public void onResult(List<ShuJuShenHePicEntity> data) {
                    dismissLoadingDialog();
                    if (data != null && data.size() > 0) {
                        path.clear();
                        for (ShuJuShenHePicEntity entity : data) {
                            path.add(entity.getImagePath() + "");
                        }
                        YinShiTuPianActivity.showTuPian(context, path);
                    } else {
                        showToast("暂无图片");
                    }
                }
            }, lifecycleSubject);
        }
    }

    private void loadData() {
        shuJuShenHeModel.queryShenHeDetail(treatmentId, new CommonObserver<List<ShuJuShenHeDetailEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                closeFrshorLoadmore();
            }

            @Override
            public void onResult(List<ShuJuShenHeDetailEntity> data) {
                adapter.replaceData(data);
                closeFrshorLoadmore();
            }
        }, lifecycleSubject);
    }

    protected RecyclerView.ItemDecoration createItemDecoration() {
        return new DefaultItemDecoration(ContextCompat.getColor(this, R.color.margin_background), 2, 2, -1);
    }

    /**
     * 关闭加载更多或者刷新
     */
    private void closeFrshorLoadmore() {
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadmore();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
    }

    private void updateShengHuaData(boolean isPass) {
        this.isPass = isPass;
        List<ShuJuShenHeDetailEntity> list = adapter.getData();
        UpdateShenHuaData submitData = new UpdateShenHuaData();
        submitData.setPatientId(patientId);
        submitData.setMeasureDate(measureDate);
        submitData.setTreatmentId(treatmentId);
        List<ShengHuaSubmitSubData> submitSubData = new ArrayList<>();
        boolean hasValue = false;
        String shuzhangya = "";
        String sousuoya = "";
        for (ShuJuShenHeDetailEntity entity : list) {
            ShengHuaSubmitSubData data = new ShengHuaSubmitSubData();
            data.setId(entity.getId());
            data.setValue(entity.getValue());
            submitSubData.add(data);
            if (!hasValue && notEmpty(entity.getValue())) {
                hasValue = true;
            }
            if ("1".equals(entity.getSort())) {
                shuzhangya = entity.getValue();
            }
            if ("2".equals(entity.getSort())) {
                sousuoya = entity.getValue();
            }
        }
        if (!hasValue) {
            showToast("请至少填写一项或多项检查指标数据");
            return;
        }
        if (notEmpty(sousuoya) != notEmpty(shuzhangya)) {
            showToast("收缩压和舒张压必须一起填写");
            return;
        }
        submitData.setInspectrecords(submitSubData);
        showLoadingDialog("提交中");
        CommonUtil.hideSoftInput(context, recyclerView);
        shuJuShenHeModel.updateShengHua(submitData, new CommonObserver<Object>() {
            @Override
            public void onError(int errType, String errMessage) {
                dismissLoadingDialog();
                showToast(errMessage);
            }

            @Override
            public void onResult(Object data) {
                shenHe();
            }
        }, lifecycleSubject);

    }

    public void pass(View view) {
        updateShengHuaData(true);
    }


    public void notPass(View view) {
        startActivity(new Intent(context, ShenHeFalseActivity.class));
    }


    private void shenHe() {
        shuJuShenHeModel.shenHe(treatmentId, remark + "", isPass ? 1 : 0, new CommonObserver<String>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(String data) {
                dismissLoadingDialog();
                showToast("提交成功");
                EventBusUtil.postEvent(new ShenHeUpdate());
                finish();
            }
        }, lifecycleSubject);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ShenHeRemarkMessage message) {
        if (message != null) {
            remark = message.getRemark();
            updateShengHuaData(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }

}
